import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_web_view/repository/favourites_repository.dart';
import 'package:flutter_web_view/scan_page.dart';
import 'package:flutter_web_view/url_input_dialog.dart';
import 'package:flutter_web_view/util/log_util.dart';
import 'package:flutter_web_view/util/share_util.dart';
import 'package:flutter_web_view/util/toast_util.dart';
import 'package:flutter_web_view/widget/browser_navigation_bar.dart';
import 'package:flutter_web_view/widget/f_webview/f_webview_strategy_factory.dart';
import 'package:flutter_web_view/widget/f_webview/webview_controller.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:async';
import 'package:url_launcher/url_launcher_string.dart';

import 'bean/favourites.dart';
import 'favourites_page.dart';

/// App内部Web浏览器页面
class BrowserPage extends StatefulWidget {
  const BrowserPage(this.url, {Key? key}) : super(key: key);

  final String url;

  @override
  State createState() => _BrowserPageState();
}

/// 生成PopupMenuItem组件
_createPopupMenuItem(IconData icon, String text, String id) {
  return PopupMenuItem<String>(
      value: id,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Icon(icon, color: Colors.blue),
          Container(
            margin: const EdgeInsets.only(left: 5),
            child: Text(text),
          ),
        ],
      ));
}

/// 生成进度条组件，进度从0 ~ 1
_createProgressBar(double progress, BuildContext context) {
  return LinearProgressIndicator(
    backgroundColor: Colors.white70.withOpacity(0),
    value: progress == 1.0 ? 0 : progress,
    valueColor: const AlwaysStoppedAnimation<Color>(Colors.blue),
  );
}

/// 外部浏览器中打开
Future<void> _launchInBrowser(String url) async {
  if (!await launchUrlString(
    url,
    mode: LaunchMode.externalApplication,
  )) {
    throw 'Could not launch $url';
  }
}

/// 显示Url输入弹窗
void _showUrlInputDialog(context, String oldUrl, Function onUpdateUrlCallback) {
  showDialog(
      context: context,
      builder: (context) {
        return UrlInputDialog(
          oldUrl,
          (newUrl) {
            return onUpdateUrlCallback(newUrl.toString());
          },
        );
      });
}

class _BrowserPageState extends State<BrowserPage> {
  FWebViewController? _webViewController;
  String? _webTitle;
  double _progress = 0;
  bool isCanGoBack = false;
  bool isCanForward = false;
  bool isFavourite = false;

  /// 跳转到二维码扫描
  void _goQrScan(context) async {
    //请求摄像头权限
    var status = await Permission.camera.request();
    if (status.isGranted) {
      //跳转到二维码扫描页面，并获取扫描结果
      String? scanResult =
          await Navigator.push(context, MaterialPageRoute(builder: (context) {
                return const ScanPage();
              })) ??
              "";
      //加载扫描结果
      if (scanResult.isNotEmpty) {
        _webViewController?.loadUrl(scanResult);
      }
    }
  }

  /// 显示Url地址输入弹窗
  void _showUrlInput(context) {
    _webViewController?.getUrl().then((url) {
      //显示Url输入弹窗
      _showUrlInputDialog(context, url.toString(), (String newUrl) {
        if (newUrl.trim().isEmpty) {
          ToastUtil.toast("请输入内容");
          return false;
        }
        //加载输入的Url
        _webViewController?.loadUrl(newUrl);
        return true;
      });
    });
  }

  /// 跳转到我喜欢的
  void _goMyFavourites(context) async {
    Favourite? favourite =
        await Navigator.push(context, MaterialPageRoute(builder: (context) {
      return const FavouritesPage();
    }));
    //加载我喜欢的
    if (favourite != null) {
      _webViewController?.loadUrl(favourite.url);
    }
  }

  /// 切换喜欢
  void _toggleFavorite(bool currentIsFavourite) async {
    var url = await _webViewController?.getUrl() ?? "";
    var title = _webTitle ?? await _webViewController?.getTitle() ?? "";
    if (currentIsFavourite) {
      FavouritesRepository.removeFavourite(url);
    } else {
      FavouritesRepository.addFavourite(url, title);
    }
    var beforeIsFavourite = currentIsFavourite;
    setState(() {
      isFavourite = !isFavourite;
    });
    if (beforeIsFavourite) {
      LogUtil.log("取消成功");
    } else {
      LogUtil.log("添加成功");
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () {
          Future<bool> canGoBack = _webViewController!.canGoBack();
          return canGoBack.then((isCanGoBack) {
            if (isCanGoBack) {
              _webViewController!.goBack();
              return false;
            } else {
              return true;
            }
          });
        },
        child: Scaffold(
          appBar: AppBar(
            leading: Row(
              children: [
                isCanGoBack
                    ? IconButton(
                        onPressed: () {
                          _webViewController?.goBack();
                        },
                        icon: const Icon(Icons.arrow_back))
                    : IconButton(
                        icon: const Icon(Icons.close),
                        onPressed: () {
                          SystemNavigator.pop();
                        })
              ],
            ),
            title: Text(_webTitle ?? "FlutterWebView"),
            actions: [
              IconButton(
                  icon: const Icon(Icons.share),
                  tooltip: '分享',
                  onPressed: () {
                    _webViewController?.getUrl().then((url) {
                      //分享
                      ShareUtil.shareText('$_webTitle\n${url.toString()}');
                    });
                  }),
              IconButton(
                  icon: const Icon(Icons.open_in_browser),
                  tooltip: '外部浏览器中打开',
                  onPressed: () {
                    _webViewController?.getUrl().then((url) {
                      _launchInBrowser(url!);
                    });
                  }),
              PopupMenuButton(
                itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
                  _createPopupMenuItem(Icons.favorite, '我的收藏', 'my_favourites')
                ],
                onSelected: (String action) {
                  switch (action) {
                    case 'my_favourites':
                      _goMyFavourites(context);
                      break;
                  }
                },
              )
            ],
          ),
          body: Column(
            children: [
              Expanded(
                  child: Stack(
                children: [
                  FWebViewStrategyFactory.getWebViewByPlatform(
                    widget.url,
                    onTitleChanged:
                        (FWebViewController controller, String? title) {
                      setState(() {
                        _webTitle = title ?? "";
                      });
                    },
                    onWebViewCreated: (FWebViewController controller) {
                      _webViewController = controller;
                    },
                    onLoadStop: (FWebViewController controller, String? url) {
                      //页面加载完毕，显示隐藏AppBar的返回键
                      controller.canGoBack().then((canGoBack) => {
                            setState(() {
                              isCanGoBack = canGoBack;
                            })
                          });
                      controller.canGoForward().then((canForward) => {
                            setState(() {
                              isCanForward = canForward;
                            })
                          });
                      //是否我喜欢的
                      FavouritesRepository.isFavourite(url.toString())
                          .then((favourite) {
                        setState(() {
                          isFavourite = favourite;
                        });
                      });
                    },
                    onProgressChanged:
                        (FWebViewController controller, int progress) {
                      //进度从0 ~ 100
                      setState(() {
                        _progress = progress / 100.0;
                      });
                    },
                  ),
                  _createProgressBar(_progress, context)
                ],
              )),
              BrowserNavigationBar(
                isCanGoBack,
                isCanForward,
                isFavourite,
                onBackCallback: (context) {
                  _webViewController?.goBack();
                },
                onForwardCallback: (context) {
                  _webViewController?.goForward();
                },
                onAddCallback: (context, longPress) {
                  if (longPress) {
                    //长按，二维码扫描
                    _goQrScan(context);
                  } else {
                    //点击输入地址
                    _showUrlInput(context);
                  }
                },
                onRefreshCallback: (context) {
                  _webViewController?.reload();
                },
                onToggleFavoriteCallback: (context, currentIsFavourite) {
                  _toggleFavorite(currentIsFavourite);
                },
              )
            ],
          ),
        ));
  }
}
